package com.ruyuan2020.im.x;

import java.util.Arrays;

/**
 * _有序数组的平方
 */
public class _22 {
        public static int[] sortedSquares(int[] nums) {
            int n = nums.length;
            int[] result = new int[n];
            int left = 0, right = n - 1;
            int index = n - 1;

            while (left <= right) {
                int leftSquare = nums[left] * nums[left];
                int rightSquare = nums[right] * nums[right];

                if (leftSquare > rightSquare) {
                    result[index] = leftSquare;
                    left++;
                } else {
                    result[index] = rightSquare;
                    right--;
                }
                index--;
            }

            return result;
        }
    public static void main(String[] args) {
        int[] nums1 = {-4, -1, 0, 3, 10};
        int[] nums2 = {-7, -3, 2, 3, 11};

        System.out.println("Sorted squares of nums1: " + Arrays.toString(sortedSquares(nums1)));
        System.out.println("Sorted squares of nums2: " + Arrays.toString(sortedSquares(nums2)));
    }
}
